package cn.fzkj.gulimall.ware.service.impl;

import cn.fzkj.common.constant.WareConstant;
import cn.fzkj.common.exception.ErrorsEnum;
import cn.fzkj.gulimall.ware.entity.PurchaseDetailEntity;
import cn.fzkj.gulimall.ware.exception.PurchaseException;
import cn.fzkj.gulimall.ware.service.PurchaseDetailService;
import cn.fzkj.gulimall.ware.service.WareSkuService;
import cn.fzkj.gulimall.ware.vo.PurchaseDoneVo;
import cn.fzkj.gulimall.ware.vo.PurchaseItemDoneVo;
import cn.fzkj.gulimall.ware.vo.PurchaseMergeVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.fzkj.common.utils.PageUtils;
import cn.fzkj.common.utils.Query;

import cn.fzkj.gulimall.ware.dao.PurchaseDao;
import cn.fzkj.gulimall.ware.entity.PurchaseEntity;
import cn.fzkj.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService detailService;
    @Autowired
    private WareSkuService skuService;

    @Override
    public boolean finishPurchase(PurchaseDoneVo vo) {

        // 1、改变采购项状态
        List<PurchaseItemDoneVo> items = vo.getItems();
        boolean flag = false;  // 采购是否存在异常
        List<PurchaseDetailEntity> updateDetailEntities = new ArrayList<>();
        for (PurchaseItemDoneVo item : items) {
            PurchaseDetailEntity entity = new PurchaseDetailEntity();
            entity.setId(item.getPurchaseDetailId());
            if (item.getStatus() == WareConstant.PurchaseDetailStatus.HAVEERROR.getStatus()){
                flag = true;
                entity.setStatus(WareConstant.PurchaseDetailStatus.HAVEERROR.getStatus());
            }else {
                entity.setStatus(WareConstant.PurchaseDetailStatus.FINISH.getStatus());
                // 3、将采购的入库
                PurchaseDetailEntity en = detailService.getPurchaseDetailById(Arrays.asList(item.getPurchaseDetailId())).get(0);
                if (en != null){
                    skuService.addStock(en.getSkuId(), en.getSkuNum(), en.getWareId());
                }
            }
            updateDetailEntities.add(entity);
        }
        detailService.updateBatchById(updateDetailEntities);

        // 2、改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(vo.getPurchaseId());
        purchaseEntity.setUpdateTime(new Date());
        if (flag){
            purchaseEntity.setStatus(WareConstant.PurchaseStatus.HAVEERROR.getStatus());
        }else {
            purchaseEntity.setStatus(WareConstant.PurchaseStatus.FINISH.getStatus());
        }
        this.updateById(purchaseEntity);

        return true;
    }

    /**
     * 领取采购单
     * @param ids 要领取的采购单id
     * @return
     */
    @Transactional
    @Override
    public boolean receivePurchases(List<Long> ids) {

        // 1、确认当前采购单处理新建/已分配状态
        List<PurchaseEntity> collect = ids.stream().map(id -> {
            return this.getById(id);
        }).filter(item -> {
            if (item.getAssigneeId() == null){
                throw new PurchaseException(ErrorsEnum.PURCHASE_DETAIL_RECEIVE_BEFORED_ASSIGN);
            }
            return item.getStatus() == WareConstant.PurchaseStatus.CREATED.getStatus() ||
                    item.getStatus() == WareConstant.PurchaseStatus.ASSIGNED.getStatus();
        }).map(item -> {
            item.setStatus(WareConstant.PurchaseStatus.RECEIVE.getStatus());
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());

        if (CollectionUtils.isEmpty(collect)){
            // 没有满足条件的采购单，默认成功
            return true;
        }

        // 2、改变采购单状态
        this.updateBatchById(collect);

        // 3、改变采购需求的状态
        collect.forEach(item -> {
            List<PurchaseDetailEntity> detailEntities = detailService.getPurchaseDetailByPurchaseId(item.getId());
            List<PurchaseDetailEntity> collect1 = detailEntities.stream().map(entity -> {
                PurchaseDetailEntity purchaseDetail = new PurchaseDetailEntity();
                purchaseDetail.setId(entity.getId());
                purchaseDetail.setStatus(WareConstant.PurchaseDetailStatus.PURCHASING.getStatus());
                return purchaseDetail;
            }).collect(Collectors.toList());
            detailService.updateBatchById(collect1);
        });
        return true;
    }

    /**
     * 合并采购需求成采购单
     * @param vo
     * @return
     */
    @Transactional
    @Override
    public boolean mergePurchase(PurchaseMergeVo vo) {
        Long purchaseId = vo.getPurchaseId();
        if (purchaseId == null){
            PurchaseEntity entity = new PurchaseEntity();
            entity.setCreateTime(new Date());
            entity.setUpdateTime(new Date());
            entity.setStatus(WareConstant.PurchaseStatus.CREATED.getStatus()); // 默认为新建状态
            this.save(entity);
            purchaseId = entity.getId();
        }

        List<Long> detailIds = vo.getItems(); // 采购需求id
        // 确认采购需求没有被合并
        List<PurchaseDetailEntity> details = detailService.getPurchaseDetailById(detailIds);
        boolean present = details.stream().anyMatch(item -> {
            if (item.getStatus() == WareConstant.PurchaseDetailStatus.CREATED.getStatus() ||
                    item.getStatus() == WareConstant.PurchaseDetailStatus.ASSIGNED.getStatus()){
                return false;
            }
            return true;
        });
        if (present){
            throw new PurchaseException(ErrorsEnum.PURCHASE_DETAIL_ALREADY_MERGED);
        }

        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = detailIds.stream().map(detailId -> {
            PurchaseDetailEntity entity = new PurchaseDetailEntity();
            entity.setId(detailId);
            entity.setPurchaseId(finalPurchaseId);
            entity.setStatus(WareConstant.PurchaseDetailStatus.ASSIGNED.getStatus());
            return entity;
        }).collect(Collectors.toList());
        boolean b = detailService.updateBatchById(collect);
        return b;
    }

    @Override
    public PageUtils getUnReceiveList(Map<String, Object> params) {

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status", 0).or().eq("status", 1)
        );

        return new PageUtils(page);

    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> queryWrapper = new QueryWrapper<>();
        /**
         * page: 1
         * limit: 10
         * key:
         * status:
         */
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)){
            queryWrapper.eq("id", key).or().like("assignee_name", key);
        }
        String status = (String) params.get("status");
        if (StringUtils.isNotEmpty(status)){
            queryWrapper.eq("status", key);
        }
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

}